'use strict';

const {
	log
} = require("console");

module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/files_mzgl/dy_tv_series/kh/gitList2 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			ma_,
			appid,
			appsecret,
			tvName,
			total_num,
			tv_id,
			pageNumber
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		if (!appsecret) {
			let appdata = await db.collection("a_appid").where({
				appid: appid,
			}).get()
			appsecret = appdata.data[0].appsecret
		}
		//获取后台生成未上传的抖音剧集
		let dbName = "dy_tv_series"; // 表名
		let odata = await vk.baseDao.select({
			dbName: dbName, // 表名
			getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			getMain: false,
			pageSize: 200,
			whereJson: { // 条件
				tv_id: tv_id,
			},
			// 按_id降序 asc 升序 desc 降序 
			sortArr: [{
				name: "seq",
				type: "asc"
			}],
		});
		console.log('传入参数', appid,
			appsecret,
			tvName,
			total_num,
			tv_id,
			pageNumber);
		res.data = odata
		// 添加标记是否填充
		odata.rows.forEach(item => {
			item.flag = false
		})
		console.log('获取的当前剧集信息', odata.total, odata.rows[0]);
		//获取accessToken
		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: appid, // id
				client_secret: appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})
		let access_token = accessToken.data.data.access_token
		console.log("看看token", access_token);
		//提取最后的数字也就是集数
		function getseq(str) {
			const regex = /\d+(?=\D*$|$)/;
			const lastMP4Index = str.lastIndexOf('.');
			const lastNumberMatch = str.slice(0, lastMP4Index).match(regex);
			return lastNumberMatch ? lastNumberMatch[lastNumberMatch.length - 1] : null;
		}

		let page_number = pageNumber || 1 //查询页码
		// 分集获取视频信息
		function outTrim(str) {
			// 使用正则表达式替换空格
			if (str) return str.replace(/\s/g, "");
		}
		let urlT = "https://open.douyin.com/api/dyc_voc/get_video_list"
		async function getVideoList(page_number) {
			let resA = await uniCloud.httpclient.request(urlT, {
				method: 'POST',
				headers: {
					"Content-Type": "application/json",
					"access-token": access_token,
				},
				data: {
					page_size: 20,
					page_number: page_number,
					env_id: 1,
					business_status: 99
				},
				dataType: 'text', // 指定返回值为json格式，自动进行parseK
			})
			resA = JSON.parse(resA.data)
			if (resA.err_msg == "应用未获得该能力") {
				console.log("aaaaa", resA);
			}
			console.log('分页------------------------------------------', page_number)
			return resA
		}
		let resStr = '' //重复的集数
		let resB = ''
		let total_tip = 0 //已添加的集数
		tvName = outTrim(tvName)
		if (tvName) {
			do {
				resB = await getVideoList(page_number);
				if (resB.err_msg == "应用未获得该能力") {
					return {
						code: 1,
						msg: "应用未获得媒资管理api能力"
					};
				}
				if (!resB.data) {
					res.msg = "参数不正确或该剧已送审，完成" + total_tip + "集";
					res.code = 1;
					break;
				}

				// 使用 Promise.all() 确保所有异步操作完成
				await Promise.all(
					resB.data.map(async (item) => {
						if (item.video_name.includes(tvName)) {
							let result = getseq(item.video_name);
							let index = result - 1;
							if (odata.rows[index].seq == result) {
								odata.rows[index].dy_cloud_id = item.vid;
								let tip = ''
								if (odata.rows[index].flag) {
									resStr = resStr + '.' + result
								} else {
									odata.rows[index].flag = true
									tip = await vk.baseDao.updateById({
										dbName: "dy_tv_series",
										id: odata.rows[index]._id,
										dataJson: {
											dy_cloud_id: item.vid,
										},
									});
									++total_tip;
								}

								console.log(
									"name",
									item.video_name,
									"集数=====",
									result,
									odata.rows[index].seq,
									"vid=====",
									item.vid,
									total_tip,
									page_number,
									"数据库操作",
									tip
								);
							}
						}
					})
				);

				++page_number;
			} while (total_tip < total_num);
		} else {
			do {
				resB = await getVideoList(page_number);
				if (resB.err_msg == "应用未获得该能力") {
					return {
						code: 1,
						msg: "应用未获得媒资管理api能力"
					};
				}
				if (!resB.data) {
					res.code = 1;
					res.msg = "参数不正确或该剧已送审，完成" + total_tip + "集";
					break;
				}

				// 使用 Promise.all() 确保所有异步操作完成
				await Promise.all(
					resB.data.map(async (item) => {
						let result = getseq(item.video_name);
						let index = result - 1;
						if (odata.rows[index].seq == result) {
							odata.rows[index].dy_cloud_id = item.vid;
							let tip = ''
							if (odata.rows[index].flag) {
								resStr = resStr + '.' + result
							} else {
								odata.rows[index].flag = true
								tip = await vk.baseDao.updateById({
									dbName: "dy_tv_series",
									id: odata.rows[index]._id,
									dataJson: {
										dy_cloud_id: item.vid,
									},
								});
								++total_tip;
							}
							console.log(
								"name",
								item.video_name,
								"集数=====",
								result,
								odata.rows[index].seq,
								"vid=====",
								item.vid,
								total_tip,
								page_number,
								"数据库操作",
								tip
							);
						}

					})
				);
				++page_number;
			} while (total_tip < total_num);
		}
		if (res.code == 0) {
			res.code = 1
			res.msg = "填充完成，已填充" + total_tip + "集";
		}

		let resStr2 = ''
		odata.rows.forEach(item => {
			if (!item.flag) resStr2 = resStr2 + '.' + item.seq
		})
		// 判断是否有缺少集数
		if (resStr2) res.msg = res.msg + resStr2 + "缺失";
		// 判断是否有重复集数
		if (resStr) res.msg = res.msg + resStr + "重复";

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}